package com.app.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.mapper.GoodsSpecsMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.GoodsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商品信息
 *
 * @author 16693103420
 * @since 2024-01-25
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FileService fileService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GoodsSpecsService goodsSpecsService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private GoodsSpecsMapper goodsSpecsMapper;
    @Autowired
    private UserService userService;

    // 查询列表
    @GetMapping("/getGoodsList")
    public Result getGoodsList(@RequestParam(defaultValue = "0") Integer page,
                               @RequestParam(defaultValue = "10") Integer limit, Integer type, String keyword,
                               @RequestParam(required = false) Integer inventory,
                               HttpServletRequest request,@RequestParam(required = false)Integer areaId) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        GoodsVo goodsVo = goodsService.getGoodsList(page, limit, type, keyword,user,areaId,inventory);
        return Result.success(goodsVo);
    }

    // 用户查询列表
    @GetMapping("/getUserGoodsList")
    public Result getUserGoodsList(@RequestParam(defaultValue = "0") Integer page,
                                   @RequestParam(defaultValue = "10") Integer limit,
                                   @RequestParam(required = false) Integer applyType,
                                   @RequestParam(required = false) Integer sort,
                                   Integer type, String name,HttpServletRequest request) {

        GoodsVo goodsVo = goodsService.getUserGoodsList(page, limit, type,applyType, name,request,sort);
        return Result.success(goodsVo);
    }

    // 用户查询商品详情
    @GetMapping("/getUserGoodsById")
    public Result getUserGoodsById(Integer id) {
        GoodsModel goods = goodsService.getGoodsById(id);
        return Result.success(goods);
    }

    //根据id查询
    @GetMapping("/getGoodsById")
    public Result getGoodsById(Integer id) {
        GoodsModel goods = goodsService.getGoodsById(id);
        if (StrUtil.isNotBlank(goods.getAreaCode())) {
            List<String> list = JSON.parseObject(goods.getAreaCode(), new TypeReference<List<String>>() {
            });
            goods.setValue(list);
        }
        return Result.success(goods);
    }

    //新增和修改
    @PostMapping("/addAndUpdateGoods")
    public Result addAndUpdateGoods(@RequestBody GoodsModel goodsModel) {
        GoodsModel Goods = goodsService.getById(goodsModel.getId());
        if (goodsModel.getValue() != null) {
            goodsModel.setAreaCode(JSON.toJSONString(goodsModel.getValue()));
        }
        //是商家
        if(goodsModel.getBussesType()==1)
        {
            if(goodsModel.getBusinessId()==null)
            {
                return Result.error(201,"请选择商家");
            }
            UserModel userModel = goodsSpecsMapper.getUserInfoByBusiness(goodsModel.getBusinessId());
            if(userModel==null)
            {
                return Result.error(201,"商家用户不存在");
            }
            goodsModel.setBusinessUserid(userModel.getId());
        }else{
            goodsModel.setBussesType(0);
            goodsModel.setBusinessUserid(null);
            goodsModel.setBusinessId(null);
        }
        if (Goods != null) {
            goodsModel.setUpdateTime(CommonHelp.getNowTimestamp());
            goodsService.updateById(goodsModel);
            return Result.success("修改成功");
        } else {
            goodsModel.setCreateTime(CommonHelp.getNowTimestamp());
            goodsService.save(goodsModel);
            return Result.success("添加成功");
        }
    }

    //根据id删除
    @GetMapping("/delGoods")
    public Result delGoods(Integer id) {
        GoodsModel goods = goodsService.getById(id);
        Integer status = goods.getStatus();
        if (status == 1) {
            return Result.error(201, "商品状态正在启售,不可删除");
        }
        goodsService.delGoods(id);
        return Result.success("删除成功");
    }

    /**
     * 获取类型列表
     *
     * @return {@link Result}
     */
    @GetMapping("/getTypeList")
    public Result getTypeList() {
        QueryWrapper<CategoryModel> categoryModelQueryWrapper = new QueryWrapper<>();
        categoryModelQueryWrapper.eq("pid", 50);
        List<CategoryModel> modelList = categoryService.list(categoryModelQueryWrapper);
        return Result.success(modelList);
    }

    /**
     * 更新状态
     *
     * @param id     id
     * @param status 状态
     * @return {@link Result}
     */
    @GetMapping("/updateStatus")
    public Result updateStatus(Integer id, Integer status) {
        GoodsModel goodsModel = goodsService.getById(id);
        if (goodsModel != null) {
            goodsModel.setStatus(status);
            goodsService.updateById(goodsModel);
            return Result.success("状态更新成功");
        } else {
            return Result.error(405,"商品不存在");
        }
    }

}

